package middleware

import (
	
	"net/http"
	"strings"
	"phoenix/gin_web/dao"
	"phoenix/gin_web/common"
	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg": "权限不足",
			})
			ctx.Abort()
			return
		}

		//有权限就对string进行处理。去除头7
		tokenString = tokenString[7:]
		
		
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
			ctx.Abort()
			return
		}
		 
		//取出claims中的用户相关的信息

		
		d := dao.GetUserDaoInstance()
		user, exist := d.GetUserByID(claims.UserId)

		if !exist {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg": "用户已注销",
			})
		}

		ctx.Set("user", user)
		ctx.Next()
	}
}